<template>
	<div id="allscreen" class="content_height">
		<TaskItem ref="TaskItem" class="task-item-container" :isRobot="isRobot" :camera="camera" :isAutoPlaySuccess="isAutoPlaySuccess" :streamAutoPlay="streamAutoPlay" :saveCustomerMessageData="saveCustomerMessageData" @switchCameraReplaceStream="switchCameraReplaceStream"></TaskItem>
		<!--1v1视频通话-->
		<div class="content_height video_content">
			<div class="content_height">
				<img src="../../static/image/updaterobot.png" class="loadagentimg" :width="screenWidth" :height="screenHeight" v-show="readyToTalkRobot && isRobot && isStreamRendering" />
				<img src="../../static/image/transfer.png" class="loadagentimg" :width="screenWidth" :height="screenHeight" v-show="isTransfer && members.length < 1" />
				<div class="waitingpage" v-show="!localPublicationId || (isTransfer && waitingNumber != 0)">
					<img src="../../static/image/loadagent.png" class="loadagentimg" :width="screenWidth" :height="screenHeight" v-show="!localPublicationId" />
					<div class="waiting" v-show="(!localPublicationId && waitingNumber != 0) || (isTransfer && waitingNumber != 0)">
						<p
							>当前共<span>{{ waitingNumber }}</span
							>人等待中</p
						>
						<p
							>您排在第<span>{{ currentPosition }}</span
							>位</p
						>
					</div>
				</div>
				<img src="../../static/image/voiceBig.png" class="voiceBgImg" :width="screenWidth" :height="screenHeight" v-show="receiveMediaType == 'audio' && localPublicationId" />
				<div :class="getVideoWateMarkPosition" v-if="videoWaterMark.showVideoWaterMark && !showPhoto">
					<img id="videoWaterMark" :src="videoWaterMark.watermark" alt="" class="videoWatermark" :height="videoWaterMarkImage.height" :width="videoWaterMarkImage.width" />
				</div>
				<template v-for="(item, index) in members">
					<div :key="index" :style="index === 1 ? getVideoBoxWithOne : getVideoBoxWithTwo">
						<div :class="getVideoAgentIdPosition" v-if="videoAgentId.showVideoAgentId && !showPhoto" :style="getAgentIdBoxTop">
							<p class="videoAgentId">工号: {{ item.user.name }}</p>
						</div>
					</div>
				</template>

				<template v-for="item in remoteStreams">
					<div :class="item.audioOnly ? 'videoWithAudio_height' : 'video_height'" :key="item.id">
						<video :class="[isRobot && members.length > 1 ? 'aiRobotVideo' : 'aivideo']" :id="item.id" autoplay controls webkit-playsinline playsinline x5-playsinline :height="remoteStreams.length > 0 ? screenHeight / remoteVideoStreamLength : screenHeight" v-show="item.id" :style="item.label.indexOf('agent') === -1 && members.length > 1 ? 'object-fit: revert;' : 'object-fit: cover;'">
						</video>
						<audio :id="item.id + 'voice'" autoplay controls :height="1" :width="1" v-show="item.id && receiveMediaType == 'audio'"> </audio>
						<img src="../../static/image/voiceBig.png" class="agent-stream-audio" :width="screenWidth" :height="remoteStreams.length > 0 ? screenHeight / remoteVideoStreamLength : screenHeight" v-show="item.mediaStreamMode == 'audio'" />
					</div>
				</template>
			</div>

			<div id="mylocalvideo">
				<div :class="showPhoto ? 'video-box-fullscreen' : 'customer-video-box'" :height="showPhoto ? screenHeight : 160" v-show="localPublicationId">
					<video controls :class="[showPhoto && callMediaType != 'audio' ? 'mecameravideo' : 'mevideo', callMediaType == 'audio' ? 'meVideo_hidden' : 'me_video']" id="customer" ref="myvideo" muted autoplay webkit-playsinline playsinline x5-playsinline x5-video-player-type="h5" x5-video-orientation="portrait" x5-video-player-fullscreen="false"> </video>
				</div>
				<img src="../../static/image/voiceSmall.png" :class="showPhoto ? 'mecameravideo' : 'mevideo'" style="z-index: 8" :height="showPhoto ? screenHeight : 160" v-show="getVoiceImgShow" />
				<img src="../../static/image/voiceSmall.png" class="voice-img" style="z-index: 8" :height="showPhoto ? screenHeight : 160" v-show="upgradeStreamMode === 'audio'" />
				<canvas id="cameracanvas" :width="screenWidth" :height="screenHeight" class="canvas" v-show="false"></canvas>
				<canvas id="canvas" :width="120" :height="160" class="canvas" v-show="false"></canvas>
			</div>

			<!-- 字幕文件 -->
			<div class="subtitle" id="subtitle" :style="getSubtitleStyle">
				<SubTitle v-if="subTitleData.length > 0 && isRobot" :subTitleData="subTitleData" :clientId="clientId" />
			</div>
			<div class="op">
				<img src="../../static/image/unaudio.png" class="opimage" @click="muted('unmute')" v-show="localPublicationId && audio_muted && !showPhoto" />
				<img src="../../static/image/audio.png" class="opimage" @click="muted('mute')" v-show="localPublicationId && !audio_muted && !showPhoto" />
				<img src="../../static/image/stopvideo.png" class="opimage" @click="hangup()" v-show="!showPhoto" />
				<img src="../../static/image/changecamera.png" class="opimage" @click="switchCameraReplaceStream()" v-show="localPublicationId && !showPhoto" />
			</div>
			<img src="../../static/image/newback.png" class="imimg" style="z-index: 20" id="switchIm" @click="gotoIm" v-show="!showPhoto" />
		</div>
		<!--观看坐席屏幕共享应用-->
		<div v-show="screenStreamShow" class="screenview" id="screen_view" :height="screenHeight">
			<screensharemark class="screensharemark" v-show="screenStreamShow" :whiteShow="whiteShow"></screensharemark>
			<!--访客不允许关闭-->
			<!--<img src="../../static/image/close.png" class="imimg" @click="closeScreenStream()">-->
		</div>

		<div id="chatIm" class="chatIm" v-show="showIM && !showPhoto && !screenstreamId">
			<newIM
				ref="imchild"
				style="width: 100%"
				@startScreenMark="startScreenMark"
				@exit="exitsession"
				:audiovideo="true"
				:members="this.members"
				@stopScreenMark="stopScreenMark"
				@HangupWithNoAgent="backToStartPage"
				@AutoHangUp="backToStartPage"
				@sureinfo="sureinfo"
				@back="back"
				@surecollectioninfo="sureinfo"
				@onTextMessage="onTextMessage"
				@agentcollectionPic="agentcollectionPic"
				@onCustomMessage="onCustomMessage"
				@showAgentVideo="back"
			/>
		</div>

		<div class="agentvideo" v-show="screenstreamId || (showIM && !showPhoto) || pdffile" ref="agentvideo"> </div>
		<!-- 当收集信息框也在时，在最上面 -->

		<!-- 收集信息 -->

		<Modal v-model="isShowCollect" :closable="false" :mask-closable="false" :title="$t('ivcs.confirm')" @on-ok="confirmInformation" @on-cancel="cancelConfirm">
			<div>
				<div>{{ $t('ivcs.agentsureinfo') }}</div>
				<div
					><span>{{ $t('ivcs.name') }}:</span>
					<span>{{ confirmInfo.name }}</span>
				</div>
				<div
					><span>{{ $t('ivcs.idcard') }}:</span>
					<span>{{ confirmInfo.ID }}</span>
				</div>
				<div
					><span>{{ $t('ivcs.mobile') }}:</span>
					<span>{{ confirmInfo.mobile }}</span>
				</div>
				<div
					><span>{{ $t('ivcs.category') }}:</span>
					<span>{{ confirmInfo.productCategory }}</span>
				</div>
				<div
					><span>{{ $t('ivcs.address') }}:</span>
					<span>{{ confirmInfo.address }}</span>
				</div>
				<div
					><span>{{ $t('ivcs.companyname') }}:</span>
					<span>{{ confirmInfo.company }}</span>
				</div>
			</div>
		</Modal>

		<!--选择摄像头-->
		<Modal v-model="showSelectCamera" :closable="false" :mask-closable="false">
			<p slot="header" style="height: 60px">
				<span style="color: #666666; font-size: 13px; height: 60px; white-space: pre-wrap">{{ $t('camera.prompt') }}</span>
			</p>
			<RadioGroup v-model="selectCameraDeviceId" vertical>
				<Radio :label="device.deviceId" v-for="(device, index) in deviceVideoList" v-bind:key="device.deviceId">
					<Icon type="social-apple"></Icon>
					<span>{{ device.label }} {{ index + 1 }}</span>
				</Radio>
			</RadioGroup>
			<div slot="footer">
				<Button type="info" size="default" class="icbc_defaultbackColor" @click="selectCamera(selectCameraDeviceId)">{{ $t('ivcs.Yes') }}</Button>
			</div>
		</Modal>
		<div class="sessionTime" v-show="callduration != 0">{{ calltime }}</div>
		<!-- <ScreenSync v-if="showScreenSyncView" class="screensync" :isCustomer="true" :url="snycUrl" :ivcsClient="ivcsClient" :messageIn="messageIn"  -->
		<ScreenSync v-if="showScreenSyncView" class="screensync" :isCustomer="true" :url="snycUrl" :onMessageOut="onScreenSyncMessage" :messageIn="messageIn" :onScreenSyncEnd="onScreenSyncEnd"> </ScreenSync>
	</div>
</template>

<script>
import ivcs from '../ivcs-sdk';
import TaskItem from '../components/TaskItem.vue';
import { postforminfo, updateforminfo, uploadFileWithFormData, savesessionform, getSystemConfig } from '../api/api';
import { formatDuring } from '../tool/tool';
import Camera from '../components/Camera';
import Sxqm from '../components/sxqm';
import newIM from '../components/newIM';
import message from '../../static/js/message';
import Screensharemark from '../components/Screensharemark';
import Forminfo from '../components/Forminfo';
import SubTitle from '../components/SubTitle';
import { getBrowserClinetInfo, dealWithBigBase64Image, agentInSessionRecord, filterAgentMember, sendMessageToRecord, filterAgentByMsg } from '../tool/util';
import _ from 'lodash';
// import ScreenSync from '@zco/screen-sync';
// import '@zco/screen-sync/dist/screen-sync.css';
import { mapState } from 'vuex';
import { getAgentIdBoxTop, getVideoBoxWithOne, getVideoBoxWithTwo, getVideoWateMarkPosition, getVideoAgentIdPosition } from '../tool/watermark';

export default {
	name: 'VideoSession',
	// eslint-disable-next-line vue/no-unused-components
	components: { Screensharemark, newIM, Sxqm, Camera, Forminfo, SubTitle, TaskItem },
	data() {
		return {
			confirmInfo: {
				name: '',
				ID: '',
				mobile: '',
				productCategory: '',
				address: '',
				company: ''
			},
			isShowCollect: false,
			calltime: '00:00:01',
			callduration: 0,
			calltimer: null,
			agentId: '', //坐席id
			//UI data
			screenWidth: window.screen.width,
			screenCanvasHeight: window.screen.height,
			screenHeight: window.innerHeight, //window.screen.availHeight,//window.screen.availHeight,
			//show data
			showscreenmark: false,
			showIM: false,
			pdffile: null, //坐席推送的合同文件
			showPhoto: false,
			audio_muted: false, //当前是否静音
			sessionId: null,
			customerStatus: 0, //0：呼叫坐席前/没有坐席  1：视频聊天中 2：坐席已结束
			camera: 'front', //摄像头正反

			//room data
			roomId: null,
			roomToken: null,
			localStream: null,
			participants: new Array(),
			subscriptions: new Array(),
			remoteStreams: [],
			localPublicationId: null,
			/*屏幕共享相关的流*/
			screenstreamId: null,
			screenstreamsubscribe: null,
			icsClient: null,
			isopenaudio: false, //是否打开声音按钮
			SwitchCameraing: false, //是否正在切换摄像头
			showSelectCamera: false,
			selectCameraDeviceId: undefined,
			deviceVideoList: [],
			isRobot: false, //是否有机器人在会话中
			isStreamRendering: false, //是否正在订阅流
			participantId: undefined,
			readyToTalkRobot: false,
			robotSubscription: null,
			quitSessionAgents: [],
			callMediaType: 'video',
			receiveMediaType: 'video',
			isTransfer: false, //转接中,
			members: [], //当前通话中的坐席
			streamAddEvent: null,
			streamEndEvent: null,
			customerJoinSessionEvent: null,
			agentQuitSessionEvent: null,
			customerQuitSessionEvent: null,
			agentJoinSessionEvent: null,
			screenStreamShow: null, //显示屏幕共享
			subTitleData: [],
			clientId: '', //当前访客在ccs中的clientId
			currentPosition: 0,
			waitingNumber: 0,
			// 同屏参数
			snycUrl: `${location.origin}/${location.pathname}/#/link `, // 同屏H5页面地址 static/screensyncH5/index.html
			showScreenSyncView: false, // 是否显示同屏窗口
			// eslint-disable-next-line no-undef
			ivcsClient: ivcs.client, // ivcs.client实例
			messageIn: {},
			assetPath: `${location.origin}/${location.pathname}/static/whiteboardimg`,
			coBrowsingCommandId: 0,
			listenner: null,
			agentClientId: '', //坐席id
			robotClientId: '', //加入会话的机器人坐席的clientId，用户信息指定对象发送
			isAutoPlaySuccess: false, //判断访客是否自动播放成功
			cmdList: {}, //坐席发送的指令队列
			whiteShow: false, //共享标注组件
			waitLabel: [], //待自动播放的label
			robotTalkStyle: '', //机器人播报方式 talk-only | hear-only | talk-hear
			//坐席id水印
			videoAgentId: {
				showVideoAgentId: false,
				position: ''
			},
			//logo水印
			videoWaterMark: {
				showVideoWaterMark: false,
				position: '',
				scale: '',
				watermark: ''
			},
			//水印图片
			videoWaterMarkImage: '',
			// 流升级模式
			upgradeStreamMode: 'video',
			ZcoSubTitle: null
		};
	},
	computed: {
		...mapState({
			messageData: state => state.message.messageData,
			customer: state => state.user.customer,
			agent: state => state.user.agent,
			agentMembers: state => state.user.agentMembers
		}),
		getSubtitleStyle() {
			return this.showPhoto ? 'visibility: hidden;' : '';
		},

		getVoiceImgShow() {
			return this.localPublicationId && this.callMediaType == 'audio' && this.receiveMediaType == 'video';
		},
		remoteVideoStreamLength() {
			let result = this.remoteStreams.filter(item => {
				return !item.audioOnly;
			});
			console.log('remoteVideoStreamLength', result);
			return result.length;
		},
		//根据图片宽高计算坐席id位置
		getAgentIdBoxTop() {
			return getAgentIdBoxTop(this.videoWaterMarkImage, this.videoWaterMark, this.videoAgentId);
		},
		//适应三方时的定位 上方
		getVideoBoxWithOne() {
			return getVideoBoxWithOne(this.videoWaterMarkImage, this.videoAgentId, this.videoWaterMark);
		},
		//适应三方时的定位 下方
		getVideoBoxWithTwo() {
			return getVideoBoxWithTwo(this.videoAgentId, this.agentMembers);
		},
		//根据position计算定位 水印logo
		getVideoWateMarkPosition() {
			return getVideoWateMarkPosition(this.videoWaterMark, this.videoAgentId);
		},
		//根据position计算位置 坐席id
		getVideoAgentIdPosition() {
			return getVideoAgentIdPosition(this.videoWaterMark, this.videoAgentId);
		}
	},
	beforeRouteLeave(to, from, next) {
		// 导航离开该组件的对应路由时调用
		// 可以访问组件实例 `this`
		if (from.name == 'videosession' && to.name == 'start') {
			//用户从聊天页面误操作 返回上一个页面了
			this.$Message.error(this.$t('ivcs.sessionback'));
			next(false); //work
		} else {
			next();
		}
	},

	beforeDestroy() {
		this.$task.clear();
		this.ZcoSubTitle.destory();
		console.log(this.$task);
	},

	watch: {
		members: {
			handler(val, oldVal) {
				console.log('members update', val, oldVal);
				if (val && val.length > 0) {
					for (const item of val) {
						console.log('user in session', item);

						if (item.user.profile.isRobot) {
							this.isRobot = true;
							break;
						} else {
							this.isRobot = false;
						}
					}
				} else {
					this.isRobot = false;
				}
			},
			deep: true
		},
		receiveMediaType(val, oldVal) {
			console.log('receiveMediaType update', val, oldVal);
			if (val === 'video') {
				this.waitLabel.forEach(item => {
					this.userGesturePlayVideo(item);
				});
			}
		},
		'$store.state.showGuideBox'(val) {
			this.showPhoto = val;
		},
		'$store.state.showIM'(val) {
			this.showIM = val;
		},
		'$store.state.pdffile'(val) {
			this.pdffile = val;
		},
		'$store.state.camera'(val) {
			this.camera = val;
		},
		//获取水印图片宽高
		'videoWaterMark.showVideoWaterMark'(val) {
			if (val) {
				this.$nextTick(() => {
					let img = new Image();
					img.src = this.videoWaterMark.watermark;
					img.onload = () => {
						this.videoWaterMarkImage = {
							height: img.height * this.videoWaterMark.scale,
							width: img.width * this.videoWaterMark.scale
						};
					};
				});
			}
		}
	},
	mounted() {
		this.onCustomMessage();
		this.initMediaType();
		// this.requestSession();
		var self = this;
		//页面刷新的事件的处理，登入登出
		window.onbeforeunload = function(e) {
			console.log(e);
			//离开房间
			e = e || window.event;
			//兼容IE8和Firefox 4之前的版本
			if (e) {
				e.returnValue = '关闭提示';
			}
			// Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
			return '';
		};
		// eslint-disable-next-line no-unused-vars
		window.onunload = function(e) {
			self.backToStartPage();
		};
	},

	destroyed() {
		this.stopCallTimer();
	},

	methods: {
		...mapState('user', ['SET_AGNET_INFO', 'SET_MEMBERS_DATA']),
		...mapState('message', ['SET_MESSAGE_DATA']),
		/*初始化业务数据*/
		initializationData() {
			this.showOptions = false;
			this.showFormRemotelink = false;
			this.showScreenSyncView = false;
			this.isShowSnCode = false;
			this.showRemotelink = false;
			this.showscreenmark = false;
			this.showImagesPreview = false;
			this.isShowSnap = false;
			this.isShowCollect = false;
			this.$Notice.info({
				title: this.$t('ivcs.confirm'),
				desc: this.$t('ivcs.agentleave'),
				duration: 10,
				top: 0
			});
		},

		onAiStartSpeak(status, resp, msgId) {
			return ivcs.client.onAiStartSpeak(status, resp, msgId);
		},

		onAiStartDone(status, resp, msgId) {
			return ivcs.client.onAiStartDone(status, resp, msgId);
		},

		onTextMessage(text) {
			return ivcs.client.onTextMessage(text);
		},

		//是否有机器人在通话中
		isRobotInSession(members) {
			if (members && members.length > 0) {
				for (const item of members) {
					console.log('user in session', item);
					if (item.user.profile.isRobot) {
						this.isRobot = true;
						break;
					} else {
						this.isRobot = false;
					}
				}
			} else {
				this.isRobot = false;
			}
		},
		/**
		 * 发送信息记录
		 *
		 */
		sendMessageRecord(businessType, message, result, info, role) {
			let data = {};
			data.businessType = businessType ? businessType : '';
			data.message = message ? message : '';
			data.result = result ? result : { code: '', message: '' };
			data.info = info ? info : {};
			data.user = {
				name: localStorage.getItem('name'),
				org: localStorage.getItem('org'),
				userId: localStorage.getItem('userId'),
				picture: localStorage.getItem('userPicture'),
				role: 'customer'
			};
			role ? role : 'agents';
			// eslint-disable-next-line no-undef
			ivcs.client.sendCustomMessage(
				data,
				role,
				success => {
					console.log('发送消息成功！' + JSON.stringify(data), success);
				},
				error => {
					console.log('发送消息失败！' + JSON.stringify(data), error);
				}
			);
		},

		/**
		 * 呼叫坐席
		 */
		requestSession() {
			let service = sessionStorage.getItem('service') ? sessionStorage.getItem('service') : '';
			let specifyAgent;
			if (localStorage.getItem('agentId') && localStorage.getItem('agentId') !== 'undefined') {
				specifyAgent = localStorage.getItem('agentId');
			} else {
				specifyAgent = '';
			}
			this.browserInfo = getBrowserClinetInfo();
			let callMediaType = sessionStorage.getItem('callMediaType') ? sessionStorage.getItem('callMediaType') : 'video';
			let receiveMediaType = sessionStorage.getItem('receiveMediaType') ? sessionStorage.getItem('receiveMediaType') : 'video';
			// 同屏呼叫过滤呼叫非机器人
			let filter =
				localStorage.getItem('screensync') == 1
					? [
							{
								attribute: '是否机器人',
								rule: 'ne',
								value: 'true'
							}
					  ] // eslint-disable-line no-mixed-spaces-and-tabs
					: null;
			// 同屏辅助标志
			let isScreenSyncMode = localStorage.getItem('screensync') == 1 ? true : false;
			let query = this.$route.query;
			let userData = {
				media: callMediaType,
				userData: {
					callCode: query.callcode ? query.callcode : '',
					service: service,
					specifyAgent: specifyAgent,
					userId: localStorage.getItem('userId'),
					callMediaType: callMediaType,
					receiveMediaType: receiveMediaType,
					fullName: localStorage.getItem('fullName'),
					gender: localStorage.getItem('gender'),
					isScreenSyncMode: isScreenSyncMode,
					clientInfo: getBrowserClinetInfo(),
					filter: filter,
					formId: this.$store.state.formId,
					name: localStorage.getItem('name'),
					customer: this.customer,
					userName: sessionStorage.getItem('username'),
					idCard: sessionStorage.getItem('idcard'),
					phoneNumber: sessionStorage.getItem('mobile'),
					homeAddress: sessionStorage.getItem('address')
				},
				clientInfo: getBrowserClinetInfo(),
				filter: filter
			};
			// eslint-disable-next-line no-undef
			// ivcs.client.requestSession(
			// 	userData,
			// 	resp => {
			// 		console.log(`'request session success',${JSON.stringify(resp)},${new Date()}`);
			// 		this.sessionId = resp.sessionId;
			// 		this.$store.commit('setSessionId', resp.sessionId);
			// 		this.clientId = resp.clientId;
			// 		sessionStorage.setItem('clientId', resp.clientId);
			// 		sessionStorage.setItem('sessionId', resp.sessionId);
			// 		this.$store.commit('SET_CUSTOMER_INFO', { ...this.customer, clientId: this.clientId });
			// 		console.log(this.customer, 'SET_CUSTOMER_INFO');
			// 		this.saveCustomerForm();
			// 		this.businessInit();
			// 		this.onCallDirection();
			// 		this.onHoldOn();
			// 		this.userEvent();
			// 		this.streamEvent();
			// 		this.inviteProgress();
			// 		this.onDropByststem();
			// 		this.systemEvent();
			// 		//监听newIm中的事件
			// 		this.$refs.imchild.onTextMessage();
			// 		this.$refs.imchild.onCustomMessage();
			// 		this.$refs.imchild.onResourceMessage();
			// 		//坐席音视频准备完，访客可以推送自己的音视频。
			// 		// eslint-disable-next-line no-undef
			// 		ivcs.client.onReadyToTalk(async resp => {
			// 			console.log('agent video ready', resp);
			// 			if (!this.localPublicationId) {
			// 				try {
			// 					// eslint-disable-next-line no-unused-vars
			// 					let initvideo = await this.initVideo();
			// 					if (localStorage.getItem('screensync') == 1) {
			// 						// 设置screensync标志
			// 						localStorage.setItem('screensync', 0);
			// 						// 同屏模式下弹出H5页面
			// 						setTimeout(() => {
			// 							this.showScreenSyncView = true;
			// 						}, 10);
			// 					}
			// 				} catch (error) {
			// 					console.log('init video error', error);
			// 				}
			// 			}
			// 			// 监听同屏消息
			// 			this.agentId = resp.from;
			// 			this.onCoBrowsing();
			// 			this.onCancelCoBrowsing();
			// 			this.onBrowsingMark();
			// 		});
			// 	},
			// 	error => {
			// 		console.log(`'request session error',${JSON.stringify(error)},${new Date()}`);
			// 		this.$Message.error({
			// 			content: error.message,
			// 			duration: 3,
			// 			top: 0
			// 		});
			// 		this.$router.push('/');
			// 	}
			// );
		},

		/**
		 * 监听坐席准备就绪
		 */
		onReadyToTalk() {
			ivcs.client.onReadyToTalk(async resp => {
				console.log('agent video ready', resp);
				if (!this.localPublicationId) {
					try {
						// eslint-disable-next-line no-unused-vars
						let initvideo = await this.initVideo();
						if (localStorage.getItem('screensync') == 1) {
							// 设置screensync标志
							localStorage.setItem('screensync', 0);
							// 同屏模式下弹出H5页面
							setTimeout(() => {
								this.showScreenSyncView = true;
							}, 10);
						}
					} catch (error) {
						console.log('init video error', error);
					}
				}
				// 监听同屏消息
				this.agentId = resp.from;
				this.onCoBrowsing();
				this.onCancelCoBrowsing();
				this.onBrowsingMark();
				//机器人坐席准备就绪，访客发送ready-to-talk
				if (this.isRobot) {
					//无需订阅才发送readytotalk
					if (this.robotTalkStyle === 'hear-only' || (!this.readyToTalkRobot && !this.robotTalkStyle)) {
						let user = {
							picture: localStorage.getItem('userPicture'),
							fullName: localStorage.getItem('fullName'),
							gender: localStorage.getItem('gender')
						};
						let tellRobotAgent = await this.readyToTalkRobotAgent(this.participantId, user, this.robotClientId);
						this.readyToTalkRobot = true;
						console.log('tell agent ready to talk result', tellRobotAgent);
					}
				}
			});
		},

		/**
		 * 收到机器人的播收音方式，决定是否需要订阅机器人
		 * @param {function} ack
		 */
		onCallDirection() {
			ivcs.client.onCallDirection(async data => {
				console.log('onCallDirection,', data, new Date());
				this.robotTalkStyle = data.data.type;
				if (this.robotTalkStyle === 'hear-only' || (!this.robotTalkStyle && !this.readyToTalkRobot)) {
					let user = {
						picture: localStorage.getItem('userPicture'),
						fullName: localStorage.getItem('fullName'),
						gender: localStorage.getItem('gender')
					};
					let tellRobotAgent = await this.readyToTalkRobotAgent(this.participantId, user, this.robotClientId);
					this.readyToTalkRobot = true;
					console.log('tell agent ready to talk result', tellRobotAgent);
				}
			});
		},

		/**
		 * 访客保存提交个人信息
		 */
		saveCustomerForm() {
			let data = {};
			data.sessionId = this.sessionId;
			data.formId = this.$store.state.formId;
			console.log(data);
			if (data.formId) {
				savesessionform(data)
					.then(res => {
						console.log(res);
					})
					.catch(error => {
						console.error(error);
						this.sendMessageRecord('system_msg', '保存资料失败', error);
						this.$Message.error({
							content: '保存资料失败',
							duration: 3
						});
					});
			}
		},

		/**
          被系统强制结束
        */
		onDropByststem() {
			// eslint-disable-next-line no-undef
			ivcs.client.onDrop(resp => {
				this.sendMessageRecord('system_msg', '被系统强制结束会话', resp);
				console.log('onDrop,,', resp);
				this.$Message.error({
					content: '被系统强制结束会话',
					duration: 3
				});
				this.backToStartPage();
			});
		},

		/**
		 * 系统异常提醒
		 * */
		systemEvent() {
			// eslint-disable-next-line no-undef
			this.systemErrorEvent = ivcs.client.addEventListener('systemError', error => {
				this.sendMessageRecord('system_msg', 'system error', error);
				console.log('system error', error);
				//  publishLocalFailed:1001,
				//  subscribeStreamFailed:1002,
				//  localStreamEnd:1003,
				//  subscribeStreamEnd:1004,
				//  zmsServerDisconnected:1005,
				//  amsSocketIoError:1006,
				//  ccsSocketIoError:1007
				if (error && error.code && error.code == 1003) {
					this.$Message.error({
						content: '访客音视频推送中断,通话结束',
						duration: 3
					});
				} else if (error && error.code && error.code == 1001) {
					this.$Message.error({
						content: '推送本地画面失败,请确认网络连接是否可用,通话结束',
						duration: 3
					});
					this.backToStartPage();
				} else if (error && error.code && error.code == 1002) {
					this.$Message.error({
						content: '订阅远端画面失败,请确认网络连接是否可,通话结束',
						duration: 3
					});
					this.backToStartPage();
				} else if (error && error.code && error.code == 1004) {
					this.$Message.error({
						content: '远端画面已结束',
						duration: 3
					});
					console.log('stream end ####', error.data, new Date());
					let subscriptionId = error.data;
					//fix subscribe end is fast than stream end
					setTimeout(() => {
						let index = _.findIndex(this.remoteStreams, o => {
							return o.subscriptionId == subscriptionId;
						});
						console.log('subscriptionId end index', index);
						if (index != -1) {
							let stream = this.remoteStreams[index];
							//重新订阅
							this.subscribeAgentStream(stream.id, stream.label);
						}
					}, 200);
				} else if (error && error.code && error.code == 1005) {
					this.$Message.error({
						content: '服务器异常，通话结束',
						duration: 3
					});
					this.backToStartPage();
				} else if (error && error.code && error.code == 1006) {
					this.$Message.error({
						content: '服务异常,通话结束,请检查网络情况',
						duration: 3
					});
					this.backToStartPage();
				} else if (error && error.code && error.code == 1007) {
					this.$Message.error({
						content: '网络异常,通话结束',
						duration: 3
					});
					this.backToStartPage();
				}
			});
		},

		//获取通话水印配置
		getSystemConfig() {
			getSystemConfig()
				.then(res => {
					console.log(res);
					if (res.status === 200) {
						res.data.list.forEach(item => {
							console.log(item);
							if (item.itemKey === 'callAgentId' && item.status) {
								this.videoAgentId = {
									showVideoAgentId: true,
									position: item.itemData.position
								};
							} else if (item.itemKey === 'callWatermark' && item.status) {
								this.videoWaterMark = {
									showVideoWaterMark: true,
									position: item.itemData.position,
									scale: item.itemData.scale,
									watermark: item.itemData.watermark
								};
							}
						});
					}
				})
				.catch(err => {
					console.log(err);
				});
		},

		/**
		 * 开启本地音视频
		 */
		async initVideo() {
			return await new Promise((resolve, reject) => {
				// eslint-disable-next-line no-undef
				ivcs.client.startVideo(
					'customer',
					this.callMediaType,
					resp => {
						console.log('start video success', resp);
						this.localPublicationId = resp.publicationId;
						this.localStream = resp.localStream;
						this.participantId = resp.roomInfo.self.id;
						this.startCalltimer();
						// 接收自定义消息
						this.onCustomMessage();
						this.getSystemConfig();
						resolve('ok');
					},
					error => {
						console.log('start video failed', error);
						reject(error);
						switch (error.code) {
							case '60022':
								error.message = this.$t('ivcs.notallowederror');
								break;
							case '60023':
								error.message = this.$t('ivcs.notfounderror');
								break;
							case '60024':
								error.message = this.$t('ivcs.notfounderror');
								break;
							case '60025':
								error.message = this.$t('ivcs.overconstrainederror');
								break;
							default:
								break;
						}
						this.errorHangup(error.message);
					}
				);
			});
		},

		/**
		 * 收到自定义消息
		 */
		onCustomMessage(data) {
			console.log(data);
			if (!data) {
				return;
			}
			let msgData = data.data || '';
			if (msgData) {
				console.log(msgData);
				switch (msgData.businessType) {
					case 'upgrade_to_video':
						this.callMediaType = msgData.info.client_voice_to_video;
						this.receiveMediaType = msgData.info.agent_voice_to_video;
						if (this.callMediaType == 'video') {
							this.voiceToVideo();
							for (let index = 0; index < this.remoteStreams.length; index++) {
								this.remoteStreams[index].audioOnly = false;
							}
						}
						break;
					case 'collect-information':
						this.sureinfo(msgData.result);
						break;
					case 'mute-stream':
						this.muted(msgData.mode, msgData.source);
						break;
					case 'upgrade-stream':
						if (msgData.clientId === this.clientId) {
							this.upgradeStream(msgData.mode, msgData.source);
						} else {
							this.remoteStreams.forEach(item => {
								console.log(item);
								if (item.clientId === msgData.clientId) {
									item.mediaStreamMode = msgData.mode;
								}
							});
						}

						break;
					default:
						break;
				}
				if (msgData.type == 'screensync' || msgData.type == 'whiteboard') {
					// 同屏消息
					this.messageIn = data.data;
				}
			}
		},
		/**
		 * 接收同屏组件消息，并发送给坐席
		 */
		onScreenSyncMessage(data) {
			if (!this.coBrowsingCommandId || this.coBrowsingCommandId <= 0) {
				//
				this.ivcsClient.sendCustomMessage(
					data,
					'all',
					() => {
						// eslint-disable-line no-unused-vars
						// console.log('发送消息成功！' + message.syncId, success);
					},
					error => {
						console.error('发送消息失败！' + data, error);
					}
				);
			} else {
				ivcs.client.responseCoBrowsing(
					this.coBrowsingCommandId,
					data.action === 'endScreenSync' ? 'done' : 'in-progress',
					data,
					this.agentId,
					success => {
						console.log('responseCoBrowsing success :', success);
					},
					error => {
						console.error('responseCoBrowsing error :', error);
					}
				);
			}
		},

		/**
		 * 收到同屏浏览<目前用于坐席端同屏辅助>
		 */
		onCoBrowsing() {
			ivcs.client.onCoBrowsing(resp => {
				if (resp && resp.data) {
					this.coBrowsingCommandId = resp.data.cmdId;
					this.agentId = resp.from;
				}
			});
		},

		/**
		 * 收到取消同屏浏览<目前用于坐席端同屏辅助>
		 */
		onCancelCoBrowsing() {
			ivcs.client.onCancelCoBrowsing(resp => {
				console.log(resp);
				this.coBrowsingCommandId = 0;
			});
		},

		/**
		 * 收到同屏浏览标注<目前用于坐席端同屏辅助下标注>
		 */
		onBrowsingMark() {
			ivcs.client.onBrowsingMark(resp => {
				// 同屏消息
				if (resp && resp.data && resp.data.data) {
					this.messageIn = resp.data.data;
				}
			});
		},

		/**
		 * 呼叫进度回调
		 */
		inviteProgress() {
			// eslint-disable-next-line no-undef
			ivcs.client.onInvitationProgress(resp => {
				this.subTitleData = [];
				console.log('invite progress', resp);
				let code = resp.code;
				let self = this;
				//code 402 = waiting
				if (this.localPublicationId) {
					console.log('in room,publicationId', this.localPublicationId);
					//Cannot be determined by whether the callback is in holdon, because this callback is faster than in holdon
					// members.length = agent members length
					if (code === '402' && this.members.length < 1) {
						//转接中，并处于排队状态,则显示排队数
						console.log('is transfer and waiting for agent join');
					} else if (code === '408') {
						this.$Message.info({
							content: self.$t('ivcs.transferFailed'),
							duration: 3
						});
					}
					return;
				}

				if (code === '401') {
					this.$Message.info({
						content: self.$t('ccs.timeout'),
						duration: 3
					});
					this.backToStartPage();
				} else if (code === '403') {
					console.log('agent is connecting');
					this.waitingNumber = 0;
				} else if (code === '404') {
					this.$Message.info({
						content: self.$t('ccs.notfound'),
						duration: 3
					});
					this.backToStartPage();
				} else if (code === '402') {
					var waitingCode = resp.waitingCode;
					this.waitingNumber = resp.waitingNumber;
					this.currentPosition = resp.position;
					if (waitingCode) {
						if (waitingCode === '1000') {
							//正在分配坐席
						} else if (waitingCode === '1001') {
							//进入排队系统
							this.$Message.info({
								content: self.$t('ccs.agentBusies'),
								duration: 3
							});
						} else if (waitingCode === '1002') {
							//指定坐席，坐席没登录
							this.$Message.info({
								content: self.$t('ccs.agentNotLogin'),
								duration: 3
							});
						} else if (waitingCode === '1003') {
							//指定坐席，坐席当前状态不可用，agentStatus=ringing/serving/notReady/otherWork
							this.$Message.info({
								content: self.$t('ccs.notAvailable'),
								duration: 3
							});
						} else if (waitingCode === '1004') {
							//指定坐席，坐席振铃时,未相应
						}
					}
				} else if (code === '405') {
					this.$Modal && this.$Modal.remove();
				} else if (code === '406') {
					this.$Message.info({
						content: self.$t('ivcs.offday'),
						duration: 3
					});
					this.backToStartPage();
				} else if (code === '407') {
					this.$Message.info({
						content: self.$t('ivcs.offtime'),
						duration: 3
					});
					this.backToStartPage();
				} else if (code === '408') {
					this.$Message.info({
						content: self.$t('ivcs.scenariodisabled'),
						duration: 3
					});
					this.backToStartPage();
				} else if (code === '411') {
					this.$Message.info({
						content: '当前呼叫码已经被接通，你的呼叫已结束',
						duration: 3
					});
					this.backToStartPage();
				}
			});
		},

		//关闭view
		closeLinkView() {
			if (this.$refs.TaskItem && this.$refs.TaskItem.showRemoteVideo) {
				this.$refs.TaskItem.showRemoteVideo = false; //推送视频组件视图
			} else if (this.$refs.TaskItem && this.$refs.TaskItem.showRemotelink) {
				this.$refs.TaskItem.showRemotelink = false; //扫码或者普通iframe
			} else if (this.$refs.TaskItem && this.$refs.TaskItem.richText) {
				this.$refs.TaskItem.richText = ''; //富文本弹窗
			}
		},

		/**
		 * 收到转接的事件
		 */
		onHoldOn() {
			// eslint-disable-next-line no-undef
			ivcs.client.onHoldOn(data => {
				this.closeLinkView();
				console.log('onhold on message,', data, new Date());
				const msg = sendMessageToRecord('hold-on', data, { id: data.fromUser.id, org: '', role: 'agent', fullName: data.fromUser.name, clientId: data.from, avatar: data.fromUser.avatar, userName: data.fromUser.name, isRobot: data.fromUser.isRobot });
				this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
				// fix while transfer ai agent,onHold is later than onJoinSession
				// if(( this.isRobot && this.members.length === 0 ) || !this.isRobot ) this.isTransfer = true;
				this.isTransfer = true;
			});
		},

		/**
		 * 流事件监听
		 */
		streamEvent() {
			// eslint-disable-next-line no-undef
			this.streamAddEvent = ivcs.client.addEventListener('onStreamAdd', streamInfo => {
				console.log('### stream add', streamInfo);
				let label = streamInfo.data.streamLabel;
				console.log('### stream add label', label);
				let audioOnly = streamInfo.data.audioOnly;
				let clientId = streamInfo.data.userInfo.clientId || '';
				if (label == 'recordScreen') {
					console.log('is record screen stream');
					return;
				}
				if (label !== '' && label !== 'screen' && label != 'customer' && label.indexOf('screen') === -1) {
					//坐席流
					this.remoteStreams.push({
						id: label,
						label: label,
						audioOnly: audioOnly,
						clientId
					});
					this.subscribeAgentStream(label, label, audioOnly);
				}
				if (label === 'customer') {
					// eslint-disable-next-line no-undef
					ivcs.client.renderStream(
						label,
						label,
						resp => {
							console.log('render customer success', resp, label, label);
						},
						error => {
							console.log('render customer error', error);
						},
						playError => {
							console.log('render play error', playError);
							this.userGesturePlayVideo(label);
						},
						onEnded => {
							console.log('render onEnded', onEnded);
						}
					);
				}
				if (label.indexOf('screen') !== -1) {
					// eslint-disable-next-line no-undef
					ivcs.client.renderStream(
						label,
						'screenmark',
						resp => {
							console.log('render screen mark stream success', resp, label, label);
							this.screenStreamShow = true;
						},
						error => {
							console.log('render error', error);
						},
						playError => {
							console.log('render play error', playError);
							this.userGesturePlayVideo(label);
						},
						onEnded => {
							console.log('render onEnded', onEnded);
						}
					);
				}
			});
			// eslint-disable-next-line no-undef
			this.streamEndEvent = ivcs.client.addEventListener('onStreamEnd', streamInfo => {
				this.sendMessageRecord('system_msg', 'onStreamEnd', streamInfo);
				console.log('onStreamEnd', streamInfo);
				let label = streamInfo.data.streamLabel;
				console.log('### onStreamEnd label', label, new Date());
				_.remove(this.remoteStreams, item => {
					return item.id === label;
				});
				this.remoteStreams.sort();
				if (label.indexOf('screen') !== -1) {
					this.screenStreamShow = false;
				}
				console.log('local remote stream', this.remoteStreams);
			});
		},

		/**
		 * 订阅完，设置每个订阅的画面的subscriptionId，后续根据断开链接，判断是否需要重新订阅
		 */

		setRemoteStreamWithSubscriptionId(subscriptionId, videoLabel) {
			let index = _.findIndex(this.remoteStreams, o => {
				return o.id == videoLabel;
			});
			console.log('local remote stream index', index);
			if (index != -1) {
				let value = this.remoteStreams[index];
				value.subscriptionId = subscriptionId;
				_.fill(this.remoteStreams, value, index, index);
			}
			console.log('local remote stream', this.remoteStreams);
		},

		/**
		 * 订阅坐席流
		 */
		subscribeAgentStream(streamLabel, videoLabel, audioOnly) {
			if (this.readyToTalkRobot) {
				this.isStreamRendering = true; //如果是机器人通话，则重新订阅新画面提示正在切换形象中
			}
			ivcs.client.renderStream(
				streamLabel,
				videoLabel,
				async resp => {
					console.log('render agent success', resp, streamLabel, videoLabel);
					this.setRemoteStreamWithSubscriptionId(resp, videoLabel);
					if (this.receiveMediaType === 'audio') {
						let audioLabel = videoLabel + 'voice';
						// 和坐席语音通话
						const srcObject = document.getElementById(videoLabel).srcObject;
						document.getElementById(audioLabel).srcObject = srcObject;
					}
					if (audioOnly) {
						let audioLabel = videoLabel + 'voice';
						const srcObject = document.getElementById(videoLabel).srcObject;
						document.getElementById(audioLabel).srcObject = srcObject;
					}
					let user = {
						picture: localStorage.getItem('userPicture'),
						fullName: localStorage.getItem('fullName'),
						gender: localStorage.getItem('gender')
					};
					if (!this.readyToTalkRobot) {
						let tellRobotAgent = await this.readyToTalkRobotAgent(this.participantId, user, this.robotClientId);
						this.readyToTalkRobot = true;
						console.log('tell agent ready to talk result', tellRobotAgent);
					}
					this.isStreamRendering = false;
				},
				error => {
					console.log('render error', error);
					this.errorHangup('订阅坐席画面失败');
					this.sendMessageRecord('system_msg', `subscribeAgentStream ${streamLabel} error`, error);
				},
				playError => {
					console.log('render play error', playError);
					this.userGesturePlayVideo(videoLabel);
				},
				onEnded => {
					console.log('render onEnded', onEnded);
				}
			);
		},

		/**
		 * 用户交互播放视频画面
		 */
		// eslint-disable-next-line no-unused-vars
		userGesturePlayVideo(label) {
			//为了保证同屏时用户能听到声音
			this.isAutoPlaySuccess = true;
			this.$Modal.warning({
				title: this.$t('ivcs.confirm'),
				content: this.$t('ivcs.autoplayError'),
				okText: this.$t('ivcs.Yes'),
				cancelText: this.$t('ivcs.No'),
				onOk: () => {
					//添加自动播放
					this.streamAutoPlay();
					this.isAutoPlaySuccess = false;
				},
				onCancel: () => {
					//添加自动播放
					this.streamAutoPlay();
				}
			});
		},

		/**
		 * 退出会话并返回到呼叫页面
		 */
		backToStartPage() {
			/** 表单填写中，若坐席挂断会话，留痕表单填写失败 */
			if (this.$refs.TaskItem.showFormRemotelink && this.$refs.TaskItem.linkType === 'form') {
				this.closeFormRemoteLink();
			}
			if (this.isScaning) {
				this.agentCancelScanCode()
					// eslint-disable-next-line no-unused-vars
					.then(val => {
						this.quitSession();
						this.$router.push('/');
					})
					.catch(error => {
						this.quitSession();
						this.$router.push('/');
						console.log(error);
					});
			} else {
				this.quitSession();
				this.$router.push('/');
			}
		},

		/**
		 * 挂断通话
		 */
		hangup() {
			var self = this;
			this.$Modal.confirm({
				title: self.$t('ivcs.confirm'),
				content: self.$t('ivcs.promteleave'),
				okText: self.$t('ivcs.Yes'),
				cancelText: self.$t('ivcs.No'),
				onOk: () => {
					self.quitSession();
					self.$router.push('/');
				},
				onCancel: () => {}
			});
		},

		/**
		 * 程序错误，导致挂断
		 */
		errorHangup(error) {
			var self = this;
			this.$Modal.confirm({
				title: self.$t('ivcs.confirm'),
				content: error,
				okText: self.$t('ivcs.Yes'),
				cancelText: self.$t('ivcs.No'),
				onOk: () => {
					self.quitSession();
					self.$router.push('/');
				},
				onCancel: () => {}
			});
		},

		/**
		 * 结束通话
		 */
		quitSession() {
			let self = this;
			this.readyToTalkRobot = false;
			/*eslint-disable */
			ivcs.client.removeEventListener('onStreamAdd', this.streamAddEvent);
			ivcs.client.removeEventListener('onStreamEnd', this.streamEndEvent);
			ivcs.client.removeEventListener('onCustomerJoinSession', this.customerJoinSessionEvent);
			ivcs.client.removeEventListener('onAgentQuitSession', this.agentQuitSessionEvent);
			ivcs.client.removeEventListener('onCustomerQuitSession', this.customerQuitSessionEvent);
			ivcs.client.removeEventListener('onAgentJoinSession', this.agentJoinSessionEvent);
			ivcs.client.removeEventListener('systemError', this.systemErrorEvent);
			window.removeEventListener('message', this.formListener, true);
			self.$store.commit('SET_MESSAGE_DATA', []);
			self.$store.commit('setSessionId', null);
			this.ZcoSubTitle && this.ZcoSubTitle.destory();
			/*eslint-enable */
			return new Promise((resolve, reject) => {
				// eslint-disable-next-line no-undef
				ivcs.client.quitSession(
					{},
					resp => {
						console.log('quit session', resp);
						resolve();
					},
					function(error) {
						console.log('error,', error);
						reject(error);
					}
				);
				this.stopCallTimer();
				this.$store.state.formId = '';
				this.remoteStreams = [];
				sessionStorage.setItem('username', '');
				sessionStorage.setItem('idcard', '');
				sessionStorage.setItem('mobile', '');
				sessionStorage.setItem('address', '');
				sessionStorage.setItem('selfimg', '');
				sessionStorage.setItem('idcardFront', '');
				sessionStorage.setItem('idcardBack', '');
				sessionStorage.setItem('bankImg', '');
				sessionStorage.setItem('company', '');
				sessionStorage.setItem('category', '');
				localStorage.setItem('userInfoFormId', '');
			});
		},

		/**
		 * session相关用户离开加入事件监听
		 */
		userEvent() {
			this.customerJoinSessionEvent = ivcs.client.addEventListener('onCustomerJoinSession', info => {
				console.log('onCustomerJoinSession', info);
			});
			// eslint-disable-next-line no-undef
			this.agentQuitSessionEvent = ivcs.client.addEventListener('onAgentQuitSession', info => {
				console.log('#### onAgentQuitSession', info.data.user, new Date());
				let data = info.data;
				this.members = _.pullAllBy(this.members, [{ id: data.id }], 'id');
				/* 坐席离开，聊天记录加入离开记录，agentMembers, 移除该坐席 */
				let agentMembers = this.agentMembers.filter(item => item.id !== data.user.id);
				let message = agentInSessionRecord(info.data);
				this.$store.commit('SET_MEMBERS_DATA', agentMembers);
				this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, message]);
				console.log('SET_MEMBERS_DATA:', this.agentMembers);
				console.log('#### onAgentQuitSession session agent members,', this.members, new Date());
				if (this.members.length === 0) {
					if (!this.isTransfer) {
						this.backToStartPage();
					}
				}
				this.initializationData();
				if (info.data && info.data.user && info.data.user.profile && info.data.user.profile.isRobot) {
					let label = 'robot';
					_.remove(this.remoteStreams, item => {
						return item.id === label;
					});
					this.remoteStreams.sort();
					this.isRobot = false;
					this.robotTalkStyle = '';
				}
				this.isRobotInSession(this.members);
			});
			// eslint-disable-next-line no-undef
			this.customerQuitSessionEvent = ivcs.client.addEventListener('onCustomerQuitSession', info => {
				console.log('onCustomerQuitSession', info);
			});
			// eslint-disable-next-line no-undef
			this.agentJoinSessionEvent = ivcs.client.addEventListener('onAgentJoinSession', async info => {
				console.log('#### onAgentJoinSession', info.data.user, new Date());
				this.members.push(info.data);

				/* 坐席加入，聊天记录加入记录，agentMembers, 增加该坐席 */
				let agentMembers = filterAgentMember(this.members);
				let message = agentInSessionRecord(info.data);
				this.$store.commit('SET_MEMBERS_DATA', agentMembers);
				this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, message]);
				console.log('#### onAgentJoinSession session agent members,', this.members, new Date());
				//when an artificial agent is transferred to an AI agent, the visitor receives the AI agent first and then receives the transfer message onHoldOn
				this.isTransfer = false;
				if (info.data && info.data.user && info.data.user.profile && info.data.user.profile.isRobot) {
					this.readyToTalkRobot = false; //修复转机器人后，无法发readytotalk消息问题
					this.isRobot = true;
					this.robotClientId = info.data.id; //robot agent clientId in ccs
					try {
						let user = {
							picture: localStorage.getItem('userPicture'),
							fullName: localStorage.getItem('fullName'),
							gender: localStorage.getItem('gender')
						};
						if (!this.localPublicationId) {
							let startVideo = await this.initVideo();
							console.log('start video result', startVideo);
						}
						// TODO wait zms update
						// emporary solution:stop render agentStream then subscribe self as robot stream and then subscribe agentStream
						console.log('tellRobotAgent participantId', this.participantId);
						await this.noticeRobotCustomerJoinRoom(user, this.robotClientId);
					} catch (error) {
						console.log('init video error', error);
						this.backToLoginPage();
					}
				}
			});
		},

		/**
		 * 停止订阅所有坐席
		 */
		stopRenderAgentStream() {
			_.forEach(this.remoteStreams, stream => {
				let subscriptionId = stream.subscriptionId;
				ivcs.client.stopRenderStream(
					subscriptionId,
					s => {
						console.log('stop render stream success', subscriptionId, s);
						//重置remoteStream的subscriptionId,防止触发1004,重新订阅坐席
						this.setRemoteStreamWithSubscriptionId('', stream.id);
					},
					e => {
						console.log('stop render stream error', subscriptionId, e);
					}
				);
			});
		},

		/**
		 * 恢复订阅所有的坐席
		 */
		restoreRenderAgentStream() {
			_.forEach(this.remoteStreams, stream => {
				this.subscribeAgentStream(stream.id, stream.label);
			});
		},

		/**
		 * 通知坐席，访客已经加入房间，可以加载机器人资源
		 */
		async noticeRobotCustomerJoinRoom(user, agentClientId) {
			let self = this;
			return await new Promise((resolve, reject) => {
				// eslint-disable-next-line no-undef
				console.log(user, agentClientId);
				ivcs.client.noticeCustomerJoinRoom(
					user,
					agentClientId,
					s => {
						console.log('noticeRobotCustomerJoinRoom success', s);
						resolve(s);
					},
					error => {
						self.sendMessageRecord('system_msg', 'noticeRobotCustomerJoinRoom failed', error);
						console.log('noticeRobotCustomerJoinRoom failed', error);
						reject(error);
					}
				);
			});
		},

		/**
		 * 告知坐席，访客已经订阅好机器人,机器人可以播报话术
		 */
		async readyToTalkRobotAgent(participantId, user, agentClientId) {
			let self = this;
			return await new Promise((resolve, reject) => {
				// eslint-disable-next-line no-undef
				ivcs.client.readyToTalk(
					participantId,
					user,
					agentClientId,
					s => {
						console.log('tell agent ready to talk success', s);
						resolve(s);
					},
					error => {
						self.sendMessageRecord('system_msg', 'tell agent ready to talk failed', error);
						console.log('tell agent ready to talk failed', error);
						reject(error);
					}
				);
			});
		},

		/**
		 * 静音/恢复控制按钮
		 */
		muted(type, source = 'audio') {
			var self = this;
			if (type == 'unmute') {
				// eslint-disable-next-line no-undef
				ivcs.client.unmute(
					source,
					function() {
						console.log(`unmute ${source} succss`);
						self.audio_muted = false;
					},
					function(error) {
						self.sendMessageRecord('system_msg', `unmute ${source} failed`, error);
						console.log(`unmute ${source} failed`, error);
					}
				);
			} else if (type == 'mute') {
				// eslint-disable-next-line no-undef
				ivcs.client.mute(
					source,
					function() {
						console.log(`mute ${source} succss`);
						self.audio_muted = true;
					},
					function(error) {
						self.sendMessageRecord('system_msg', `mute ${source} failed`, error);
						console.log(`mute ${source} failed`, error);
					}
				);
			}
		},

		//坐席取消扫码
		agentCancelScanCode(id) {
			//清除截图定时器
			if (this.$refs.TaskItem && this.$refs.TaskItem.$refs.ScanCode) {
				clearInterval(this.$refs.TaskItem.$refs.ScanCode.scannerTimer);
			}

			//切换摄像头关闭扫码
			return new Promise((resolve, reject) => {
				if (this.camera === 'back') {
					ivcs.client.switchCamera(
						stream => {
							this.$store.commit('setCamera', 'front');
							this.$refs.myvideo.srcObject = stream;
							this.$refs.myvideo.load();
							this.$refs.myvideo.play();
							resolve();
						},
						err => {
							console.log(err);
							reject(err);
						}
					);
				} else {
					this.$store.commit('setCamera', 'back');
				}
				this.$refs.TaskItem.showScanCodeView = false;
				if (id) {
					this.$task.filter(id);
				}
			});
		},

		/**
		 * 选择摄像头
		 */
		switchCamera() {
			return new Promise((resolve, reject) => {
				ivcs.client.switchCamera(
					stream => {
						resolve(stream);
					},
					err => {
						console.log(err);
						this.sendMessageRecord('system_msg', 'client switch camera err', err);
						reject(err);
						this.$Message.error(this.$t('camera.switchError'));
					},
					end => {
						console.log('switchCamera end',end);
					},
					'customer',
					playerror => {
						console.log('switchCamera playerror',playerror);
					}
				);
			});
		},

		/**
		 * 返回登录页面
		 */
		backToLoginPage() {
			this.quitSession();
			this.$router.push('/');
		},

		//初始化呼叫类型
		initMediaType() {
			this.callMediaType = sessionStorage.getItem('callMediaType') ? sessionStorage.getItem('callMediaType') : 'video';
			this.receiveMediaType = sessionStorage.getItem('receiveMediaType') ? sessionStorage.getItem('receiveMediaType') : 'video';
		},

		//开启定时器
		startCalltimer() {
			var self = this;
			if (!this.calltimer) {
				this.calltimer = setInterval(function() {
					self.callduration += 1000;
					self.calltime = formatDuring(self.callduration);
				}, 1000);
			}
		},

		//停止定时器
		stopCallTimer() {
			if (this.calltimer) {
				clearInterval(this.calltimer);
				this.callduration = 0;
				this.calltimer = null;
			}
		},
		//切换摄像头
		switchCameraReplaceStream() {
			if (this.callMediaType === 'audio') {
				return;
			}
			this.switchCamera()
				.then(stream => {
					this.camera = this.camera === 'front' ? 'back' : 'front';
					console.log('stream', stream);
					// document.getElementById('customer').srcObject = stream;
					// document.getElementById('customer').load();
					// document.getElementById('customer').play();
					// document.addEventListener(
					// 	'WeixinJSBridgeReady',
					// 	() => {
					// 		document.getElementById('customer').play();
					// 		this.$refs.myvideo.play();
					// 		console.log('WeixinJSBridgeReady s');
					// 	},
					// 	false
					// );
					// 呼叫码呼叫
					if (this.$route.query && this.$route.query.callcode) {
						console.log('callcode call', this.$route.query.callcode);
						this.streamAutoPlay();
					}
				})
				.catch(err => {
					console.log(err);
					console.log('switchCameraReplaceStream error', err);
				});
		},

		//监听坐席发送静默等待的消息
		onSilentWaiting() {
			ivcs.client.onSilentWaiting(data => {
				console.log('onSilentWaiting', data);
			});
		},

		upgradeStream(mode, source) {
			if (source === 'upgrade-audio') {
				this.videoToVoice();
			} else if (source === 'upgrade-video') {
				this.voiceToVideo();
			}
		},

		//语音升级成视频
		voiceToVideo() {
			//Fixed bug where Apple 14.3 + version WeChat applet built-in browser could not display robots
			let self = this;
			this.streamAutoPlay();
			// eslint-disable-next-line no-undef
			ivcs.client.voiceToVideo(
				resp => {
					this.upgradeStreamMode = 'video';
					console.log('voiceToVideo success', resp);
				},
				error => {
					self.sendMessageRecord('system_msg', 'voiceToVideo error', error);
					console.log('voiceToVideo error', error);
				}
			);
		},

		// 视频降级语音
		videoToVoice() {
			let self = this;
			this.streamAutoPlay();
			// eslint-disable-next-line no-undef
			ivcs.client.videoToVoice(
				resp => {
					this.upgradeStreamMode = 'audio';
					console.log('videoToVoice success', resp);
				},
				error => {
					self.sendMessageRecord('system_msg', 'videoToVoice error', error);
					console.log('videoToVoice error', error);
				}
			);
		},

		/**
		 * 流自动播放
		 */
		streamAutoPlay() {
			_.forEach(this.remoteStreams, function(stream) {
				let video = document.getElementById(stream.id);
				video && video.play();
				console.log('auto play success', stream.id);
			});
			let me = document.getElementById('customer');
			me && me.play();
			let screen = document.getElementById('screen');
			screen && screen.play();
			let screenmark = document.getElementById('screenmark');
			screenmark && screenmark.play();
		},

		/**
		 * 开启屏幕标注
		 */
		startScreenMark(code) {
			if (!this.whiteShow) {
				this.whiteShow = true;
				this.$Message.info({
					content: this.$t('ivcs.agentmark'), //"坐席正在标注屏幕，建议横屏观看",
					duration: 5
				});
			}
			message.$emit('receiveMessage', code);
		},

		/**
		 * 停止屏幕标注
		 */
		stopScreenMark() {
			this.whiteShow = false;
			this.$Message.info(this.$t('ivcs.agentmarkend'));
		},

		/**
		 * 确认用户信息
		 */
		sureinfo(text) {
			this.isShowCollect = true;
			var reg = new RegExp('&quot;', 'g');
			console.log(text);
			var string = JSON.stringify(text).replace(reg, '"');
			console.log(string);
			this.confirmInfo = JSON.parse(string.toString());
		},

		/**
		 * 提交个人确认信息
		 */
		confirmInformation() {
			var self = this;
			let result = {};
			if (!this.confirmInfo.formId) {
				postforminfo(this.confirmInfo)
					.then(function(resp) {
						if (resp.data.code == 200) {
							localStorage.setItem('userInfoFormId', resp.data.data.id);
							//发送表单id给坐席
							console.log('postform success', resp);
							result.code = 200;
							result.formId = resp.data.data.id;
							self.$store.state.formId = result.formId;
							result.data = resp.data;
							result.message = '确认提交个人资料';
							self.$Message.success(self.$t('session.success'));
							self.sendMessageRecord('send_form', '提交个人信息成功', result);
							self.saveCustomerForm();
						}
					})
					.catch(function(error) {
						console.log('confirm information,error,', error);
						result.code = 400;
						result.error = error.msg || error.message || error;
						self.sendMessageRecord('send_form', '提交个人信息失败', result);
						self.$Message.error(error);
					});
			} else {
				updateforminfo(this.confirmInfo.formId, this.confirmInfo)
					.then(resp => {
						if (resp.data.code === 200) {
							localStorage.setItem('userInfoFormId', this.confirmInfo.formId);
							//发送表单id给坐席
							console.log('postform success', resp);
							result.code = 200;
							result.formId = this.confirmInfo.formId;
							self.$store.state.formId = result.formId;
							result.data = resp.data;
							result.message = '确认提交个人资料';
							self.$Message.success(self.$t('session.success'));
							self.sendMessageRecord('send_form', '提交个人信息成功', result);
							self.saveCustomerForm();
						}
					})
					.catch(error => {
						console.log('confirm information,error,', error);
						result.code = 400;
						result.error = error.msg || error.message || error;
						self.sendMessageRecord('send_form', '提交个人信息失败', result);
						self.$Message.error(error);
					});
			}
		},
		cancelConfirm() {
			this.isShowCollect = false;
		},

		/*坐席采集照片信息
		 * agentcollectionPic=
		 * */
		agentcollectionPic(type) {
			let picType = type;
			let u = navigator.userAgent;
			let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //操作系统是否为ios
			//将截取图片赋值给img标签的src
			if (!isIOS) {
				let track;
				if (this.localStream.mediaStream) {
					track = this.localStream.mediaStream.getVideoTracks()[0];
				} else {
					track = this.localStream.getVideoTracks()[0];
				}
				let imageCapture = new ImageCapture(track);
				imageCapture
					.takePhoto()
					.then(blob => {
						console.log('blob', blob);
						try {
							this.blobToDataURL(blob, imageBase64 => {
								if (blob.size / 1024 > 1024) {
									dealWithBigBase64Image(
										imageBase64,
										1920,
										resultBase64 => {
											this.sendCollectionImage(resultBase64, picType);
										},
										1024,
										100
									);
								} else {
									this.sendCollectionImage(imageBase64, picType);
								}
							});
						} catch (e) {
							this.$Message.error(e);
							this.sendMessageRecord('system_msg', '坐席采集照片信息失败', e);
						}
					})
					.catch(error => {
						console.log(error);
						var canvas = document.getElementById('cameracanvas');
						var context = canvas.getContext('2d');
						var video = document.getElementById('customer');
						context.drawImage(video, 0, 0, this.screenWidth, (this.screenWidth * 4) / 3);
						var imageBase64 = canvas.toDataURL('image/png');
						this.sendCollectionImage(imageBase64, picType);
					});
			} else {
				var canvas = document.getElementById('cameracanvas');
				var context = canvas.getContext('2d');
				var video = document.getElementById('customer');
				context.drawImage(video, 0, 0, this.screenWidth, (this.screenWidth * 4) / 3);
				var imageBase64 = canvas.toDataURL('image/png');
				this.sendCollectionImage(imageBase64, picType);
			}
		},

		blobToDataURL(blob, callback) {
			let a = new FileReader();
			a.onload = function(e) {
				callback(e.target.result);
			};

			a.readAsDataURL(blob);
		},

		sendCollectionImage(imageUrl, picType) {
			var para;
			if (picType == 1) {
				para = {
					frontPhoto: imageUrl
				};
			} else if (picType == 2) {
				para = {
					backPhoto: imageUrl
				};
			} else if (picType == 3) {
				para = {
					bankCardPhoto: imageUrl
				};
			} else if (picType == 4) {
				para = {
					selfie: imageUrl
				};
			}
			let formId = this.$store.state.formId;
			let result = {};
			var self = this;
			updateforminfo(formId, para)
				.then(function(resp) {
					console.log('update application info resp', resp);
					if (resp.data.code == 200) {
						result.code = 200;
						result.formId = formId;
						result.message = '图片更新成功';
						self.sendMessageRecord('send_form', '图片已更新', result); //告诉坐席图片更新了
					} else {
						result.code = 400;
						result.data = resp.data;
						self.sendMessageRecord('send_form', '图片更新失败', result);
					}
				})
				.catch(function(error) {
					console.log('updateforminfo error', error);
					result.code = 400;
					result.error = error.msg || error.message || error;
					self.sendMessageRecord('send_form', '图片更新失败', result);
				});
		},

		async uploadFile(obj, name) {
			return new Promise((resolve, reject) => {
				var formData = new FormData();
				formData.append('file', obj, name);
				uploadFileWithFormData(formData)
					.then(function(resp) {
						console.log('uploadFile success', resp);
						resolve(resp.data.data.url);
					})
					.catch(function(error) {
						reject(error);
						console.log('uploadFile failed', error);
						this.sendMessageRecord('system_msg', 'uploadFile failed', error);
					});
			});
		},

		/*show im ui*/
		gotoIm() {
			this.showIM = true;
			this.streamAutoPlay();
		},

		/*结束会话*/
		exitsession() {
			var self = this;
			this.$Modal.success({
				title: self.$t('ivcs.serverend'),
				okText: self.$t('ivcs.Yes'),
				onOk: function() {
					self.backToStartPage();
				},
				onCancel: function() {}
			});
		},

		/**
		 * 返回
		 */
		back() {
			this.showIM = false;
			this.streamAutoPlay();
		},
		/**
		 * 关闭同屏组件
		 */
		onScreenSyncEnd() {
			this.showScreenSyncView = false;
			// 切换到视频通话
			this.callMediaType = 'video';
			this.receiveMediaType = 'video';
			this.voiceToVideo();
			//自动播放video
			this.streamAutoPlay();
		},

		/** 指令业务相关 */

		/** 监听资源分享指令 */
		onSendViewResource() {
			ivcs.client.onSendViewResource(data => {
				this.saveAgentMessageData(data, 'view');
			});
		},

		/** 监听NLP */
		onNlpNode() {
			ivcs.client.onNlpNode(data => {
				if (data && data.data && data.data.data && data.data.data.isStart) {
					this.saveAgentMessageData(data, 'third-nlp');
				}
			});
		},

		/** 监听推送引导框指令 */
		onSendGuideBox() {
			ivcs.client.onSendGuideBox(data => {
				this.saveAgentMessageData(data, 'show-guide-box');
			});
		},

		/** 监听推送截图指令 */
		onScreenSnapshot() {
			ivcs.client.onScreenSnapshot(data => {
				this.saveAgentMessageData(data, 'get-screenshot');
			});
		},

		/** 监听手写签名 */
		onInviteHandWriting() {
			ivcs.client.onInviteHandWriting(data => {
				this.saveAgentMessageData(data, 'get-handwriting');
			});
		},

		/** 监听坐席推送表单 */
		onSendOnlineForm() {
			ivcs.client.onSendOnlineForm(data => {
				this.saveAgentMessageData(data, 'fill-form');
			});
		},

		/** 监听坐席发送屏幕共享 */
		onScreenShare() {
			ivcs.client.onScreenShare(data => {
				this.saveAgentMessageData(data, 'get-screenshot');
			});
		},

		/** 监听坐席共享标注 */
		onScreenMark() {
			ivcs.client.onScreenMark(data => {
				this.saveAgentMessageData(data, 'screen-mark');
			});
		},

		/**	监听坐席请求地理位置 */
		onRequestCustomerLocation() {
			ivcs.client.onRequestCustomerLocation(data => {
				this.saveAgentMessageData(data, 'get-geo-location');
			});
		},

		/**	监听坐席请求扫码 */
		onRequestCustomerScanCode() {
			ivcs.client.onRequestCustomerScanCode(data => {
				this.saveAgentMessageData(data, 'scan-code');
			});
		},

		/** 监听坐席内容确认消息 */
		onConfirm() {
			ivcs.client.onConfirm(data => {
				this.saveAgentMessageData(data, 'confirm');
			});
		},

		/** 监听坐席选项判断 */
		onMakeChoice() {
			ivcs.client.onMakeChoice(data => {
				this.saveAgentMessageData(data, 'make-choice');
			});
		},

		/** 坐席取消选项判断 */
		onCancelMakeChoice() {
			ivcs.client.onCancelMakeChoice(data => {
				this.saveAgentMessageData(data, 'peer-cancel');
			});
		},

		/** 坐席停止共享标注 */
		onCancelScreenMark() {
			ivcs.client.onCancelScreenMark(data => {
				this.saveAgentMessageData(data, 'peer-cancel');
			});
		},

		/** 坐席取消扫码请求 */
		onCancelCustomerScanCode() {
			ivcs.client.onCancelCustomerScanCode(data => {
				this.saveAgentMessageData(data, 'peer-cancel');
			});
		},

		/** 坐席取消签名 */
		onCancelHandWriting() {
			ivcs.client.onCancelHandWriting(data => {
				this.saveAgentMessageData(data, 'peer-cancel');
			});
		},

		/** 坐席取消表单推送 */
		onCancelOnlineForm() {
			ivcs.client.onCancelOnlineForm(data => {
				this.saveAgentMessageData(data, 'peer-cancel');
			});
		},
		/** 坐席取消汇总确认 */
		onCancelConfirm() {
			ivcs.client.onCancelConfirm(data => {
				this.saveAgentMessageData(data, 'peer-cancel');
			});
		},

		/** 坐席取消在线资源分享 */
		onCancelViewReource() {
			ivcs.client.onCancelViewReource(data => {
				this.saveAgentMessageData(data, 'peer-cancel');
			});
		},

		/** 坐席取消屏幕共享 */
		onCancelScreenShare() {
			ivcs.client.onCancelScreenShare(data => {
				this.saveAgentMessageData(data, 'peer-cancel');
			});
		},

		//接收AI机器人走完当前节点后，返回访客处理该节点的过程和结果数据
		onWorkflowProgress() {
			ivcs.client.onWorkflowProgress(
				res => {
					if (res.data.modType === 'soundReception') {
						/** 收音模板留痕 */
						this.saveAgentMessageData(res, 'sound-reception');
					}
					console.log(res, 'onWorkflowProgress Success');
				},
				err => {
					console.log(err, 'onWorkflowProgress Error');
				}
			);
		},

		//混流中移除录像文件
		removeSnapshotInMixStream() {
			ivcs.client.removeSnapshotInMixStream(
				'all',
				res => {
					console.log(res, 'removeSnapshotInMixStream Success');
				},
				err => {
					console.log(err, 'removeSnapshotInMixStream Error');
				}
			);
		},

		// 指令初始化
		businessInit() {
			this.onSendViewResource();
			this.onInviteHandWriting();
			this.onSendOnlineForm();
			this.onScreenShare();
			this.onSendGuideBox();
			this.onScreenSnapshot();
			this.onRequestCustomerLocation();
			this.onRequestCustomerScanCode();
			this.onCancelCustomerScanCode();
			this.onCancelScreenMark();
			this.onCancelMakeChoice();
			this.onCancelOnlineForm();
			this.onCancelHandWriting();
			this.onCancelConfirm();
			this.onCancelViewReource();
			this.onMakeChoice();
			this.onConfirm();
			this.onScreenMark();
			this.onWorkflowProgress();
			this.onNlpNode();
			this.onCancelScreenShare();
		},

		// 解析业务指令
		parseBusiness(data) {
			const cmd = data.data.cmd;
			const type = data.type;
			// 确认业务指令
			if (type === 'peer-cmd') {
				switch (cmd) {
					case 'view':
						this.parseViewResource(data);
						break;
					case 'show-guide-box':
						this.$task.enqueue({ data: '', cmdId: data.data.cmdId, clientId: data.from, type: 'show-guide-box' });
						break;
					case 'get-screenshot':
						this.$task.enqueue({ data: '', cmdId: data.data.cmdId, clientId: data.from, type: 'get-screenshot' });
						break;
					case 'get-handwriting':
						this.$task.enqueue({ data: '', cmdId: data.data.cmdId, clientId: data.from, type: 'get-handwriting' });
						break;
					case 'scan-code':
						this.$task.enqueue({ data: '', cmdId: data.data.cmdId, clientId: data.from, type: 'scan-code' });
						break;
					case 'get-geo-location':
						this.$task.enqueue({ data: '', cmdId: data.data.cmdId, clientId: data.from, type: 'get-geo-location' });
						break;
					case 'fill-form':
						this.$task.enqueue({ data: data.data.data, cmdId: data.data.cmdId, clientId: data.from, type: 'fill-form' });
						break;
					case 'make-choice':
						this.$task.enqueue({ data: data.data.data, cmdId: data.data.cmdId, clientId: data.from, type: 'make-choice' });
						break;
					case 'confirm':
						this.$task.enqueue({ data: data.data.data.content, cmdId: data.data.cmdId, clientId: data.from, type: 'confirm' });
						break;
					case 'screen-mark':
						this.startScreenMark();
						break;
					default:
						break;
				}

				// 取消业务指令
			} else if (type === 'peer-cancel') {
				switch (cmd) {
					case 'scan-code':
						this.agentCancelScanCode(data.data.id);
						break;
					case 'get-handwriting':
						this.$refs.imchild.showhandsign = false;
						break;
					case 'fill-form':
						this.$refs.TaskItem.showFormRemotelink = false;
						this.$task.filter(data.data.id);
						break;
					case 'confirm':
						this.$refs.TaskItem.showImagesPreview = false;
						this.$task.filter(data.data.id);
						break;
					case 'screen-mark':
						this.stopScreenMark();
						break;
					case 'make-choice':
						this.$refs.TaskItem.showOptions = false;
						this.$task.filter(data.data.id);
						break;
					case 'view':
						//判断dom节点是否存在，存在则收到cancel指令将对应视图设为false
						if (this.$refs.TaskItem && this.$refs.TaskItem.showMessageSummaryView) {
							this.removeSnapshotInMixStream();
							this.$refs.TaskItem.showMessageSummaryView = false;
						} else if (this.$refs.TaskItem && this.$refs.TaskItem.$refs.ScanCode) {
							this.$refs.TaskItem.$refs.ScanCode.isShowSnCode = false;
						} else if (this.$refs.TaskItem && this.$refs.TaskItem.showFormRemotelink) {
							this.$refs.TaskItem.showFormRemotelink = false;
						}
						this.$task.filter(data.data.id);
						break;
					default:
						break;
				}
			}
		},

		// 处理资源分享类型业务
		parseViewResource(data) {
			let resource = data.data.data;
			switch (resource.type) {
				case 'page':
					this.$task.enqueue({ data: data.data.data, cmdId: data.data.cmdId, clientId: data.from, type: 'page' });
					break;
				case 'paper':
					this.$task.enqueue({ data: data.data.data, cmdId: data.data.cmdId, clientId: data.from, type: 'paper' });
					break;
				case 'audio':
					break;
				case 'video':
					this.$task.enqueue({ data: data.data.data, cmdId: data.data.cmdId, clientId: data.from, type: 'video' });
					break;
				case 'scanCode':
					this.$task.enqueue({ data: resource, cmdId: data.data.cmdId, clientId: data.from, type: 'WaitingRead' });
					break;
				case 'messageSummary':
					if (resource.nodeType === 'waitingReadNode') {
						this.$task.enqueue({ data: resource, cmdId: data.data.cmdId, clientId: data.from, type: 'WaitingRead' });
					}
					break;
				case 'richtext':
					this.$task.enqueue({ data: data.data.data.data, cmdId: data.data.cmdId, clientId: data.from, type: 'richtext' });
					break;
				case 'other':
					break;
				default:
					break;
			}
		},

		/** 存储聊天信息 */
		saveAgentMessageData(data, type) {
			this.cmdList[type] = data.data.cmdId;
			let agentInfo = filterAgentByMsg(data.from, this.agentMembers);
			this.$store.commit('SET_AGENT_INFO', { ...agentInfo });
			const msg = sendMessageToRecord(type, data, this.agent);
			this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
			this.$refs.imchild.scrollToBottom();
			this.$refs.imchild.setMsgTimer();
			this.parseBusiness(data);
		},
		saveCustomerMessageData(status, type, result) {
			if (status === 'in-progress' || (type === 'view' && !result)) {
				return;
			}
			let data = { data: {} };
			data.data.cmd = type;
			data.data.status = status;
			data.data.result = result;
			const msg = sendMessageToRecord(type, data, this.customer);
			this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
			this.$refs.imchild.scrollToBottom();
			this.$refs.imchild.setMsgTimer();
		}
	}
};
</script>

<style scoped>
.scancode_alert {
	position: absolute;
	top: 8%;
	transform: translate(13%, 10px);
	width: 80%;
	z-index: 2000;
}
.scancode_alert_message {
	display: flex;
	font-weight: bold;
}

.aivideo {
	width: 100%;
	position: relative;
	background: rgba(208, 208, 208, 1);
	object-fit: cover;
	/* height: 100%; */
}

.aiRobotVideo {
	width: 100%;
	position: relative;
	background: rgba(0, 0, 0, 1);
}

.screenvideo {
	width: 100%;
	/*height: 100%;*/
	position: relative;
	background: rgba(208, 208, 208, 1);
	overflow: scroll;
	/*object-fit: cover;*/
}

.screenview {
	z-index: 20;
	position: absolute;
	left: 0px;
	top: 0px;
	width: 100%;
	height: 100%;
}

.ai2video {
	width: 100%;
	/*height: 50%;*/
	position: relative;
	background: rgba(208, 208, 208, 1);
	object-fit: cover;
	background-color: #2b85e4;
}

.imimg {
	width: 36px;
	height: 26px;
	position: absolute;
	left: 20px;
	top: 20px;
	z-index: 8;
}

.closeimg {
	width: 30px;
	height: 30px;
	position: absolute;
	right: 10px;
	top: 50px;
	z-index: 8;
}

.mevideo {
	touch-action: none;
}
.customer-video-box {
	width: 120px;
	height: 160px;
	position: absolute;
	right: 10px;
	top: 20px;
	/*background-color: yellow;*/
	cursor: move;
	z-index: 7;
	overflow: hidden;
}
.video-box-fullscreen {
	position: absolute;
	width: 100%;
	height: 100%;
	z-index: 7;
	cursor: move;
	top: 0;
	right: 0;
}
.customer-video-box video {
	width: 100%;
	height: 100%;
}

.meVideo_hidden {
	width: 1px !important;
	height: 1px !important;
	position: absolute;
	right: 10px;
	top: 20px;
	cursor: move;
	z-index: 7;
	touch-action: none;
}

.mecameravideo {
	width: 100%;
	height: 100%;
	cursor: move;
	touch-action: none;
	object-fit: cover;
}
.voice-img {
	position: absolute;
	right: 10px;
	top: 10px;
}

.agentsamllvideo {
	width: 120px;
	height: 160px;
	position: absolute;
	right: 10px;
	top: 40px;
	background-color: rgba(208, 208, 208, 1);
	cursor: move;
	z-index: 7;
	touch-action: none;
	object-fit: contain;
}

.agentsamllvideo1 {
	width: 120px;
	height: 160px;
	position: absolute;
	right: 10px;
	top: 200px;
	background-color: rgba(208, 208, 208, 1);
	cursor: move;
	z-index: 7;
	object-fit: contain;
	touch-action: none;
}

.agentvideo {
	width: 100%;
	left: 0px;
	top: 0px;
	position: absolute;
	z-index: 8;
}

.op {
	position: absolute;
	width: 100%;
	height: 50px;
	bottom: 10px;
	left: 0px;
	display: flex;
	z-index: 10;
	flex-direction: row;
	justify-content: space-around;
	align-items: center;
}

.opimage {
	width: 50px;
	height: 50px;
}

.sessionTime {
	position: absolute;
	width: 20%;
	height: 50px;
	top: 20px;
	right: 50px;
	z-index: 7;
	text-align: right;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #bababa;
}

.pdffile {
	width: 100%;
	/*height:600px;*/
	position: absolute;
	left: 0;
	top: 0px;
	z-index: 7;
}

.loadimg {
	position: absolute;
	width: 80%;
	height: 80%;
	z-index: 2;
	top: 5%;
	left: 10%;
	object-fit: contain;
	z-index: 8;
}

.loadagentimg {
	object-fit: cover;
	z-index: 0;
}

.voiceBgImg {
	object-fit: cover;
	z-index: 1;
}

.openaduiodiv {
	width: 100%;
	height: 60px;
	position: absolute;
	bottom: 50%;
	z-index: 10;
}

.openaudio {
	width: 60px;
	height: 60px;
	margin: 0 auto;
	position: relative;
}

.remotevideolink {
	z-index: 100;
	width: 100%;
	height: 100%;
	position: fixed;
}

.remotelink {
	z-index: 100;
	width: 100%;
	height: 100%;
	/*width: 90%;*/
	/*height: 80%;*/
	/*left: 5%;*/
	/*top:10%;*/
	position: fixed;
}

#guide-video {
	object-fit: cover;
	object-position: center center;
	z-index: 5;
	position: absolute;
	top: 0;
	left: 0;
}

.chatIm {
	z-index: 9999;
	width: 100%;
	position: absolute;
	left: 0;
	top: 0;
	background: white;
}

.waiting {
	position: absolute;
	top: 60%;
	left: 50%;
	transform: translate(-50%, -50%);
	font-size: 14px;
	font-family: PingFangSC-Regular, PingFang SC;
	color: #ffffff;
}
.waiting span {
	font-size: 20px;
	font-family: Arial Bold;
	color: #ff7845;
	display: inline-block;
	margin-left: 4px;
	margin-right: 4px;
}

.subtitle {
	position: absolute;
	width: 100%;
	bottom: 70px;
	z-index: 10;
}
/* .task-item-container {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 200;
} */
.agent-stream-audio {
	position: absolute;
	left: 0;
	top: 0;
	z-index: 1;
	object-fit: cover;
}

.content_height {
	height: 100%;
}

.video_content {
	overflow: hidden;
	position: relative;
}

.video_height {
	height: 50%;
	position: relative;
}

.videoWithAudio_height {
	display: none;
}

.screensync {
	position: absolute;
	top: 0;
	z-index: 1000;
	overflow: hidden;
}
.videoAgentId {
	/* background: #000000; */
	background-color: rgba(0, 0, 0, 0.75);
	border-radius: 2px;
	font-size: 12px;
	color: #ffffff;
	font-weight: 400;
	line-height: 16px;
	padding: 2px 12px;
}
.videoWatermark {
	/* padding-bottom: 8px; */
}
.nw {
	position: absolute;
	z-index: 9;
	left: 16px;
	top: 50px;
}
.n {
	position: absolute;
	z-index: 9;
	top: 50px;
	left: 50%;
	transform: translate(-50%);
}
.ne {
	position: absolute;
	z-index: 9;
	top: 50px;
	right: 16px;
}
.sw {
	position: absolute;
	z-index: 9;
	bottom: 90px;
	left: 16px;
}
.s {
	position: absolute;
	z-index: 9;
	bottom: 90px;
	left: 50%;
	transform: translate(-50%);
}
.se {
	position: absolute;
	z-index: 9;
	bottom: 90px;
	right: 16px;
}
.agentId-waterMark-nw {
	position: absolute;
	z-index: 9;
	left: 16px;
	top: 85px;
	margin-top: 8px;
}
.agentId-waterMark-n {
	position: absolute;
	z-index: 9;
	top: 85px;
	left: 50%;
	transform: translate(-50%);
}
.agentId-waterMark-ne {
	position: absolute;
	z-index: 9;
	top: 85px;
	right: 16px;
}
.waterMark-agentId-sw {
	position: absolute;
	z-index: 9;
	bottom: 120px;
	left: 16px;
}
.waterMark-agentId-s {
	position: absolute;
	z-index: 9;
	bottom: 120px;
	left: 50%;
	transform: translate(-50%);
}
.waterMark-agentId-se {
	position: absolute;
	z-index: 9;
	bottom: 120px;
	right: 16px;
}
</style>
